import 'package:flutter/material.dart';
import 'package:flutter2/http/api.dart';
import 'package:flutter2/http/dio_manager.dart';
import 'package:flutter2/main.dart';
import 'package:flutter2/model/order_entity.dart';
import 'package:flutter2/ui/guide.dart';
import 'package:flutter2/ui/tab.dart';
import 'package:flutter2/utils/route.dart';
import 'package:flutter2/utils/system_bar.dart';
import 'package:flutter2/widget/title_bar.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

final ValueNotifier<int> notifier = ValueNotifier(0);

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with RouteAware {
  Widget _widget = Container();
  int index = -1;

  @override
  void initState() {
    resetId();
    super.initState();
    getData();
    addLife(this);
  }

  getData() {
    DioManager.request<List<OrderEntity>>(
      autoDismiss: false,
      path: HttpApi.orderList,
      onSuccess: (data) {
        if (data != null && data.isNotEmpty) {
          if (index == -1) index = 0;
          _widget = MainTabPage(
            onTap: (value) {
              index = value;
              setState(() {});
            },
          );
        } else {
          index = -1;
          _widget = GuidePage();
          EasyLoading.dismiss();
        }
        setState(() {});
      },
    );
  }

  String getTitle() {
    if (index == 0) {
      return "订单";
    } else if (index == 1) {
      return "我的";
    } else {
      return "";
    }
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
      value: systemUiOverlayStyle,
      child: Scaffold(
        extendBodyBehindAppBar: true,
        appBar: index >= 0
            ? TitleBar.buildAppBar(
                title: getTitle(),
                showBack: false,
                backgroundColor: index == 0 ? Colors.white : Colors.transparent,
              )
            : null,
        body: _widget,
      ),
    );
  }

  @override
  void didPopNext() {
    super.didPopNext();
    resetId();
    getData();
    notifier.value++;
  }

  @override
  void dispose() {
    super.dispose();
    routerObserver.unsubscribe(this);
  }
}
